<template>
  <div style="margin-top: 50px">
    <el-form :model="state" :rules="rules" ref="productInfoForm" label-width="120px" class="form-inner-container" size="small">
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader v-model="selectProductCateValue[0]" :options="productCateOptions" @change="categoryIdUpdate"> </el-cascader>
      </el-form-item>
      <el-form-item label="商品名称：" prop="name">
        <el-input v-model="state.name"></el-input>
      </el-form-item>
      <el-form-item label="副标题：" prop="subTitle">
        <el-input v-model="state.subTitle"></el-input>
      </el-form-item>
      <el-form-item label="商品品牌：" prop="brandId">
        <el-cascader v-model="selectProductBrandValue[0]" :options="brandOptions" @change="handleBrandChange"> </el-cascader>
      </el-form-item>
      <el-form-item label="商品介绍：">
        <el-input :autoSize="true" v-model="state.description" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="商品货号：">
        <el-input v-model="state.productSn"></el-input>
      </el-form-item>
      <el-form-item label="商品售价：">
        <el-input v-model="state.price"></el-input>
      </el-form-item>
      <el-form-item label="市场价：">
        <el-input v-model="state.originalPrice"></el-input>
      </el-form-item>
      <el-form-item label="商品库存：">
        <el-input v-model="state.stock"></el-input>
      </el-form-item>
      <el-form-item label="计量单位：">
        <el-input v-model="state.unit"></el-input>
      </el-form-item>
      <el-form-item label="商品重量：">
        <el-input v-model="state.weight" style="width: 300px"></el-input>
        <span style="margin-left: 20px">克</span>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="state.sort"></el-input>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" size="default" @click="handleNext('productInfoForm')">下一步，填写商品促销</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { fetchListWithChildren } from '@/plugins/productCate'
import { fetchList as fetchBrandList } from '@/plugins/brand'
import { reactive, ref, onBeforeMount, computed, watch, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  value: Object,
  isEdit: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['nextStep'])

let state = reactive(props.value)

let productId = computed(() => state.id)

const vue = getCurrentInstance()

const hasEditCreated = ref(false)
//选中商品分类的值
let selectProductCateValue = reactive([])
let productCateOptions = reactive([])
let selectProductBrandValue = reactive([])
let brandOptions = reactive([])
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
  ],
  subTitle: [{ required: true, message: '请输入商品副标题', trigger: 'blur' }],
  productCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
  brandId: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商品介绍', trigger: 'blur' }],
  requiredProp: [{ required: true, message: '该项为必填项', trigger: 'blur' }]
}

watch(productId, newValue => {
  if (!props.isEdit) return
  if (hasEditCreated.value) return
  if (newValue === undefined || newValue == null || newValue === 0) return
  handleEditCreated()
})

onBeforeMount(() => {
  getProductCateList()
  getBrandList()
})

function categoryIdUpdate(value) {
  if (value != null && value.length === 2) {
    state.productCategoryId = value[1]
    state.productCategoryName = getCateNameById(state.productCategoryId)
    selectProductCateValue[0] = value[1]
  } else {
    state.productCategoryId = null
    state.productCategoryName = null
  }
}

//处理编辑逻辑
function handleEditCreated() {
  if (state.productCategoryId != null) {
    selectProductCateValue.push(state.cateParentId)
    selectProductCateValue.push(state.productCategoryId)
  }
  hasEditCreated.value = true
}
function getProductCateList() {
  fetchListWithChildren().then(response => {
    let list = response.data
    if (list != null && list != undefined) {
      for (let i = 0; i < list.length; i++) {
        let children = []
        if (list[i].children != null && list[i].children.length > 0) {
          for (let j = 0; j < list[i].children.length; j++) {
            children.push({ label: list[i].children[j].name, value: list[i].children[j].id })
          }
        }
        productCateOptions.push({ label: list[i].name, value: list[i].id, children: children })
      }
    }
    selectProductCateValue.push(state.productCategoryId)
  })
}
function getBrandList() {
  fetchBrandList({ pageNum: 1, pageSize: 100 }).then(response => {
    brandOptions = []
    let brandList = response.data.list
    if (brandList != null && brandList) {
      for (let i = 0; i < brandList.length; i++) {
        brandOptions.push({ label: brandList[i].name, value: brandList[i].id })
      }
    }
    selectProductBrandValue[0] = state.brandId
  })
}
function getCateNameById(id) {
  let name = null
  for (let i = 0; i < productCateOptions.length; i++) {
    for (let j = 0; j < productCateOptions[i].children.length; j++) {
      if (productCateOptions[i].children[j].value === id) {
        name = productCateOptions[i].children[j].label
        return name
      }
    }
  }
  return name
}

function handleNext(formName) {
  vue.ctx.$refs[formName].validate(valid => {
    if (valid) {
      emits('nextStep', state)
    } else {
      ElMessage({
        message: '验证失败',
        type: 'error',
        duration: 1000
      })
      return false
    }
  })
}

function handleBrandChange(val) {
  let brandId = val[0]
  let brandName = ''
  for (let i = 0; i < brandOptions.length; i++) {
    if (brandOptions[i].value === brandId) {
      brandName = brandOptions[i].label
      break
    }
  }
  state.brandName = brandName
  state.brandId = brandId
}
</script>

<style scoped></style>
